package Test;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator; 
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AES  {
	public static void main(String[] args) throws Exception {   
		//KeyGenerator提供对称密钥生成器的功能，支持各种算法
        KeyGenerator keygen;      
	    //SecretKey负责保存对称密钥
		SecretKey deskey,deskey1;
	    //Cipher负责完成加密或解密工作
        Cipher c;               
	    Security.addProvider(new com.sun.crypto.provider.SunJCE());         
	    //实例化支持AES算法的密钥生成器，算法名称用AES         
	    keygen = KeyGenerator.getInstance("AES");         
	    //生成密钥
        deskey = keygen.generateKey();
        deskey1 = keygen.generateKey();
        //生成Cipher对象，指定其支持AES算法
        c = Cipher.getInstance("AES");                                   
	    String msg = "郭克华_安全编程技术";        
		System.out.println("明文是：" + msg);                 
		//根据密钥，对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式
        c.init(Cipher.ENCRYPT_MODE, deskey);         
		byte[] src = msg.getBytes();         
		//加密，结果保存进enc         
		byte[] enc = c.doFinal(src);
		byte[] key = deskey.getEncoded();
		System.out.println("密文是：" + new String(enc));
		System.out.println("密钥是："+new String(key));
		SecretKeySpec Sp = new SecretKeySpec(key,"AES");
		//根据密钥，对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式
        c.init(Cipher.DECRYPT_MODE, Sp);
		//解密，结果保存进dec         
		byte[] dec = c.doFinal(enc);        
		System.out.println("解密后的结果是：" + new String(dec));        
		} 
}